package com.yanfan.iot.ruleEngine;

import com.alibaba.fastjson2.JSON;
import com.dtflys.forest.http.ForestRequest;
import com.yanfan.common.utils.StringUtils;
import com.yanfan.framework.utils.RedisUtils;
import com.yanfan.http.service.HttpClientFactory;
import com.yanfan.iot.domain.Bridge;
import com.yanfan.iot.domain.HttpClient;
import com.yanfan.iot.service.IBridgeService;
import com.yanfan.iot.service.IHttpClientService;
import com.yanfan.mqttclient.PubMqttClient;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.Duration;
import java.util.Objects;

@LiteflowComponent("httpBridge")
public class HttpBridge extends NodeComponent {

    @Autowired
    private IHttpClientService httpClientService;
    @Autowired
    private IBridgeService bridgeService;
    @Autowired
    private PubMqttClient mqttClient;

    @Override
    public void process() throws Exception {
        // 获取上下文对象
        MsgContext cxt = this.getContextBean(MsgContext.class);
        Integer id = cxt.getData("httpBridgeID");
        Bridge bridge = bridgeService.selectBridgeById(Long.valueOf(id));
        if (bridge != null && Objects.equals(bridge.getEnable(), "1")) {
            if (bridge.getDirection() == 1) {
                String cacheKey = "httpBridge:" + bridge.getId() + ":" + bridge.getRoute();
                Boolean isSend = RedisUtils.getCacheObject(cacheKey);
                // 重复的消息不重复执行，1秒之内只允许发送一次，防止桥接的mqtt topic 与 自己的服务器主题一致，导致出现循环
                if (Objects.isNull(isSend) || !isSend) {
                    mqttClient.publish(0, false, cxt.getTopic(), cxt.getData("params"));
                    RedisUtils.setCacheObject(cacheKey, true, Duration.ofSeconds(1));
                }
            } else if (bridge.getDirection() == 2) { // 推送数据
                HttpClient config = JSON.parseObject(bridge.getConfigJson(), HttpClient.class);
                ForestRequest request = HttpClientFactory.instance(httpClientService.buildHttpClientConfig(config));
                if (StringUtils.isNotEmpty(config.getRequestBody())) {
                    request.addBody(cxt.placeholders(config.getRequestBody()));
                } else {
                    request.addBody(cxt.getPayload());
                }
                request.execute();
            }
        }
    }
}
